using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Threading.Tasks;
using WMSSystem.YSL;
using WMSSystem.YSL.Interfance;

namespace WMSSystem.Web.Middleware
{
    /// <summary>
    /// JWT认证中间件
    /// 自动解析JWT令牌中的用户信息并添加到请求上下文中
    /// 优化后只处理必要的用户信息：id、userName、phoneNumber、realName
    /// </summary>
    public class JwtMiddleware
    {
        private readonly RequestDelegate _next;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next">下一个中间件</param>
        public JwtMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// 中间件处理方法
        /// </summary>
        /// <param name="context">HTTP上下文</param>
        /// <returns>任务</returns>
        public async Task InvokeAsync(HttpContext context)
        {
            var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();

            if (!string.IsNullOrEmpty(token))
            {
                // 从令牌中获取用户信息（只包含必要信息）
                var userInfo = JwtTokenHelper.GetUserFromToken(token);
                
                if (userInfo != null)
                {
                    // 将用户信息添加到当前请求的上下文中
                    context.Items["CurrentUser"] = userInfo;
                    context.Items["UserId"] = userInfo.Id.ToString();
                    context.Items["UserName"] = userInfo.UserName;
                    context.Items["RealName"] = userInfo.RealName;
                    context.Items["PhoneNumber"] = userInfo.PhoneNumber;
                }
            }

            await _next(context);
        }
    }
} 